<% list_id         = "list_#{random_dom_id}"
   list_class      = options[:class] ? "list #{options[:class]}" : 'list'
   toolbar         = options[:toolbar].presence || nil
   list_name       = toolbar && toolbar[:list_name]
   hash_param_name = list_name || 'list_item'
   pagination      = options[:paginate].presence || nil
   header          = options[:header].presence || nil
   footer          = options[:footer].presence || nil
   new_link        = options[:new_link].presence
   new_link        = nil unless new_link.present? && dto_allowed? %>
<div id="<%= list_id %>" class="<%= list_class %> <%= 'list-paginated' if pagination %>"
 <%= raw %(data-paginate-url="#{pagination[:url]}" data-paginate-size="#{pagination[:size]}" data-paginate-offset="") if pagination %> >
  <% if header || pagination %>
    <div class="list-header <%= 'hide' if pagination %>">
      <% if pagination %>
        <div class="paginate-header">
          <span class="summary">&nbsp;</span>
          <%= link_to_function(icon('refresh'), 'list_paginate(this, "refresh")', :class => 'refresh') %>
        </div>
      <% end %>
      <%= header if header %>
    </div>
  <% end %>

  <%= render 'base/shared/list_toolbar', :toolbar => toolbar, :menu => options[:menu], :pagination => pagination if toolbar %>
  <div class="list-body" data-hash-param-name="<%= hash_param_name %>">
    <ul>
      <%= raw(list_content) %>
    </ul>
  </div>
  <% if footer || pagination || new_link %>
    <div class="list-footer">
      <% if new_link %>
        <div class="new-link">
          <%= new_link %>
        </div>
      <% end %>

      <%= footer if footer %>

      <% if pagination %>
        <div class="paginate-footer">
          <%= link_to_function("more", 'list_paginate(this, "add")', :class => 'btn load-next', :style => 'display:none') %>
          <%= link_to_function(icon('spinner', 'Loading...', 'fa-spin'), '', :class => 'btn disabled loading', :style => 'display:none') %>
        </div>
      <% end %>
    </div>
  <% end %>
</div>
<script type="text/javascript">
  if (!window.mark_current_list_item) {
    var CURRENT_ITEM_CLASS = "current";

    window.mark_current_list_item = function(source, item_id, no_hash) {
      var el_id = item_id ? ("item_" + item_id) : null;
      source.up('ul').childElements().each(function(item) {
        if ((el_id && item.id == el_id) || (!el_id && !item.id)) {
          item.addClassName(CURRENT_ITEM_CLASS);
        }
        else {
          item.removeClassName(CURRENT_ITEM_CLASS);
        }
      });

      if (!no_hash) {
        setHashParam($j(source).parents('.list-body').attr('data-hash-param-name'), item_id);
      }
    };

    window.clear_current_list_item = function(list) {
      list.childElements().each(function(item) {
        item.removeClassName(CURRENT_ITEM_CLASS);
      });

      setHashParam($j(list).parents('.list-body').attr('data-hash-param-name'), null);
    };

    window.toggle_select_item = function(source) {
      source = $j(source);
      source.toggleClass('fa-check-square-o');
      source.toggleClass('fa-square-o');
      $j(source.parents('li')[0]).toggleClass(CURRENT_ITEM_CLASS);
      var list = $j($j(source).parents('.list')[0]);
      if (selected_items(list).length) {
        enable_list_menu(list);
      }
      else {
        disable_list_menu(list);
      }
    };

    window.select_all_items = function(source) {
      var list = $j($j(source).parents('.list')[0]);
      list.find(".list-body > ul > li:visible").addClass(CURRENT_ITEM_CLASS);
      list.find("li:visible i.select").addClass("fa-check-square-o").removeClass('fa-square-o');
      enable_list_menu(list);
    };

    window.unselect_all_items = function(source) {
      var list = $j($j(source).parents('.list')[0]);
      list.find(".list-body > ul > li:visible").removeClass(CURRENT_ITEM_CLASS);
      list.find("li:visible i.select").addClass("fa-square-o").removeClass("fa-check-square-o");
      disable_list_menu(list);
    };

    window.selected_item_ids = function(source) {
      var ids = [];
      var list = $j($j(source).parents('.list')[0]);
      selected_items(list).each(function(index, item) {
        ids.push(item.id.substring(5));
      });
      return ids;
    };

    window.selected_items = function(list) {
      return list.find(".list-body > ul > li:visible").has("i.select.fa-check-square-o");
    };

    window.toggle_compact = function(source, action) {
      var btn = $j(source);
      var i = btn.find("i");
      var expanding = action ? (action === 'expand') : i.hasClass("fa-angle-double-down");
      i.siblings("span").html(expanding ? " Collapse" : " Expand");
      i.toggleClass("fa-angle-double-down fa-angle-double-up");
      var list = btn.parents('.list');
      var items = list.find(".list-body > ul > li .middle");
      if (expanding) {
        i.addClass("fa-angle-double-up").removeClass("fa-angle-double-down");
        items.show();
        list.find(".list-body > ul > li i.fa-angle-down").removeClass("fa-angle-down").addClass("fa-angle-up")
      }
      else {
        i.addClass("fa-angle-double-down").removeClass("fa-angle-double-up");
        items.hide();
        list.find(".list-body > ul > li i.fa-angle-up").removeClass("fa-angle-up").addClass("fa-angle-down")
      }
      if (localStorage) {
        localStorage.setItem(LOCAL_STORAGE_KEY_PREFIX + list.find(".list-toolbar").attr("list-name") + "_list_compact", expanding ? 'expand' : 'compact');
      }
    };

    window.addEventListener("hashchange",
                    function () {
                      $j(".list-body").each(function (i, l) {
                        var list = $j(l);
                        var hash_param_name = list.attr('data-hash-param-name');
                        var hash_param_value = getHashParam(hash_param_name);
                        list_process_hash_param(list.closest(".list"), hash_param_value);
                      });
                    });

    window.list_paginate = function(source, mode) {
      var listDiv = $j(source).closest('.list-paginated'),
          offset  = listDiv.attr('data-paginate-offset'),
          size    = parseInt(listDiv.attr('data-paginate-size'));

      var refreshIcon = listDiv.find(".refresh i");
      if (refreshIcon.hasClass("fa-spin")) {
        return;
      }
      refreshIcon.addClass("fa-spin");

      if (mode == 'refresh' || mode == 'startover') {
        offset = "";
      }

      listDiv.find('.list-toolbar').find('input, a').prop('disabled', true);
      listDiv.find('.paginate-footer .btn.load-next').hide();
      listDiv.find('.paginate-footer .btn.loading').show();

      var data = {size: size, offset: offset, list_id: listDiv.attr('id')};
      if (listDiv.has('.list-toolbar')[0]) {
        var sort = get_list_sort(listDiv);
        if (sort) {
          var field = sort['field'];
          if (field) {
            data['sort'] = {};
            data['sort'][field] = sort['order'] || 'asc';
          }
        }

        var list_filter = get_list_filter(listDiv);
        if (list_filter) {
          var filterValue = list_filter['value'];
          if (filterValue) {
            var split = filterValue.split(/:|=/);
            data['filter'] = {query: split.length > 1 ? split.join(':') : '*' + filterValue + "*"};
          }
        }
      }

      $j.ajax({
        url:   listDiv.attr('data-paginate-url'),
        type:  'GET',
        data:  data,
        error: function () {
          listDiv.find('.list-toolbar').show();
          listDiv.find('.list-toolbar').find('input, a').prop('disabled', false);
          listDiv.find(".refresh i").removeClass("fa-spin");
          listDiv.find('.paginate-footer .btn.loading').hide();
          // Maybe error is due to bad filter, try to reset it.
          if (get_list_filter(listDiv)['value']) {
            set_list_filter(listDiv, "");
          }
        }
      });
    };

    window.list_paginate_update = function(list, content, total_count, content_size, offset, next_offset) {
      var listDiv = $j(list).closest('.list-paginated');
      if (next_offset) {
        listDiv.attr('data-paginate-offset', next_offset);
        if (!offset) {
          listDiv.find(".list-body > ul > li").remove();
        }
      }
      else {
        listDiv.attr('data-paginate-offset', offset + content_size);
        listDiv.find(".list-body > ul > li:nth-child(n+" + (offset + 1) + ")").remove();
      }
      listDiv.find(".list-body > ul").append(content);
      listDiv.find('.paginate-header span.summary').html("Showing " + list.find(".list-body > ul > li:visible").length + (total_count < 0 ? "" : " of " + total_count));
      listDiv.find('.list-header').show();
      listDiv.find('.list-toolbar').show();
      listDiv.find('.list-toolbar').find('input, a').prop('disabled', false);
      listDiv.find('.paginate-footer .btn.loading').hide();
      if (content_size >= parseInt(listDiv.attr('data-paginate-size'))) {
        listDiv.find('.paginate-footer .btn.load-next').show();
      }
      listDiv.find(".refresh i").removeClass("fa-spin");
      var listItemId = getHashParam(listDiv.find('.list-body').attr('data-hash-param-name'));
      if (listItemId) {
        listDiv.find("#item_" + listItemId.gsub(/\W/, '') + ":not(.current) .target a").click();
      }
    };

    window.list_process_hash_param = function(list, hash_param_value) {
      if (hash_param_value) {
        var split = hash_param_value.split('::');
        if (split.length == 2 && split[0].toLowerCase() == 'filter' && split[1]) {
          set_list_filter(list, split[1]);
        }
        else {
          var current = list.find("#item_" + hash_param_value);
          if (current[0]) {
            if (!current.hasClass(CURRENT_ITEM_CLASS)) {
              current.find("div.target a").click();
            }
          }
          else {
            list.find("li." + CURRENT_ITEM_CLASS).removeClass(CURRENT_ITEM_CLASS);
            if (list.hasClass('list-paginated')) {
              set_list_filter(list, hash_param_value);
            }
          }
        }
      }
    }
  }

  (function () {
    var listDiv = $j("#<%= list_id %>"),
        listItemId = getHashParam("<%= hash_param_name %>");
    <% if toolbar %>
      list_toolbar_init(listDiv);

      <% if pagination %>
        if (listItemId) {
          list_process_hash_param(listDiv, listItemId);
        }

        listDiv.bind('sortChanged', function (e) {
          list_paginate(e.target, "startover");
        });

        listDiv.bind('filterChanged', function (e) {
          var listDivX = $j(e.target);
          var filterValue = get_list_filter(listDivX)['value'];
          setTimeout(function() {
            if (get_list_filter(listDivX)['value'] == filterValue) {
              list_paginate(listDivX, "startover")
            }
          }, 500);
        });
      <% end %>
    <% end %>

    <% if pagination %>
      list_paginate(listDiv, "add");
    <% else %>
      if (listItemId) {
        $j("#<%= list_id %> #item_" + listItemId + " .target a").click();
      }

      <% selected_id = options[:selected_item] %>
      <% if selected_id.present? %>
        $j("#<%= list_id %> #item_<%= selected_id %> .target a").click();
      <% end %>
    <% end %>
  })();
</script>
